<template>
	<div class="staff_box">
		<div class="staff_title">员工管理</div>
		
		<!-- 功能按钮 -->
		<div class="staff_function">
			<el-badge value="417" class="item">
				<el-button @click="filterByType('entry')">入职</el-button>
			</el-badge>
			<el-badge :value="12" class="item">
				<el-button type="danger" @click="filterByType('leave')">离职</el-button>
			</el-badge>
			<el-badge value="229" class="item">
				<el-button @click="filterByType('long-term')">长期派遣</el-button>
			</el-badge>
			<el-badge :value="74" class="item">
				<el-button @click="filterByType('short-term')">短期派遣</el-button>
			</el-badge>
			<el-badge value="113" class="item">
				<el-button @click="filterByType('trainee')">学员</el-button>
			</el-badge>
			<el-badge :value="8" class="item">
				<el-button @click="filterByType('duplicate')">重复人员</el-button>
			</el-badge>
			<el-button style="margin-left: 20px;">重置</el-button>
			<el-button type="danger" @click="batchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
			<el-button type="success" style="margin-left: 12%;">导出员工</el-button>
			<el-button type="primary" style="margin-left: 8%;">导入员工</el-button>
		</div>

		<!-- 搜索和新增区域 -->
		<div class="search-add">
			<div class="search_box">
				<el-input
					v-model="searchForm.name"
					class="name_search input"
					placeholder="请输入员工姓名"
					:suffix-icon="Search"
					@input="handleSearch"
				/>
				
				<!-- 公司名称 -->
				<el-select 
  v-model="searchForm.company" 
  clearable 
  class="input" 
  placeholder="请选择公司"
  filterable
  :filter-method="filterCompanyOptions"
  @change="handleSearch"
  @visible-change="onCompanySelectVisibleChange"
  @clear="onCompanySelectClear"
>
  <el-option
    v-for="item in filteredCompanyOptions"
    :key="item.value"
    :label="item.label"
    :value="item.value">
  </el-option>
</el-select>

				<!-- 项目名称 -->
				<el-input
					v-model="searchForm.project"
					class="item_search input"
					placeholder="请输入项目名称"
					:suffix-icon="Search"
					@input="handleSearch"
				/>

				<!-- 树形菜单档级 -->
				<el-tree-select
					class="input"
          clearable
					v-model="searchForm.level"
					:data="treeLevelData"
					:render-after-expand="false"
					style="width: 240px"
					placeholder='请选择档级'
					@change="handleSearch"
				/>

				<!-- 请选择证书 -->
				<el-select 
					v-model="searchForm.certificate" 
					clearable 
					class="input" 
					placeholder="请选择证书"
					@change="handleSearch"
				>
					<el-option
						v-for="item in certificateOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select>

				<!-- 请选择年月 -->
				<el-date-picker 
					class="input"
					v-model="searchForm.month"
					type="month"
					placeholder="请选择年月"
					@change="handleSearch"
				/>
			</div>
			<div class="add_box">
				<el-button 
					color="#0052CC" 
					@click="showAddForm = true"
					:disabled="isAdding"
				>
					新增
				</el-button>
			</div>
		</div>

		<!-- 表格 -->
		<el-table 
			border 
			:data="pagedEmployees" 
			style="width: 100%;margin-top:2%;" 
			max-height="450" 
			ref="tableRef"
			@selection-change="handleSelectionChange"
			:loading="tableLoading"
		>
			<el-table-column type="selection" width="55"/>
			<el-table-column fixed prop="name" label="姓名" width="100">
				<template #default="scope">
					<el-button type="primary" link @click="openEmployeeDrawer(scope.row)">
						{{ scope.row.name }}
					</el-button>
				</template>
			</el-table-column>
			<el-table-column fixed prop="base_pay" label="岗位工资" width="100" />
			<el-table-column prop="grade_title" label="岗位档级" width="100" />
			<el-table-column prop="birthday" label="生日" width="120" />
			<el-table-column prop="tel" label="手机号" width="120" />
			<el-table-column prop="idcard" label="身份证号" width="180" />
			<el-table-column prop="title" label="项目名称" width="150" />
			<el-table-column prop="account" label="公司名称" width="150" />
			<el-table-column prop="political_status" label="政治面貌" width="100" />
			<el-table-column prop="address" label="籍贯" width="100" />
			<el-table-column prop="record" label="学历" width="80" />
			<el-table-column prop="create_time" label="创建时间" width="160" />
			<el-table-column prop="status" label="员工状态" width="100" />
			<el-table-column prop="layout" label="用工形式" width="100" />
			<el-table-column prop="start_time" label="入职时间" width="120" />
			<el-table-column prop="time_section" label="合同区间" width="160" />
			<el-table-column prop="end_time" label="离职时间" width="120" />
			<el-table-column prop="agreement_num" label="合同期限" width="100" />
			<el-table-column prop="bank_card" label="银行卡号" width="180" />
			<el-table-column prop="bank" label="开户行" width="120" />
			<el-table-column fixed="right" label="操作" width="120">
				<template #default="scope">
					<el-button 
						link 
						type="danger" 
						size="small" 
						@click="deleteRow(scope.row)"
						:disabled="loadingIds.includes(scope.row.id)"
					>
						<i class="el-icon"/> 更多
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		
		<!-- 分页组件 -->
		<div class="pagination-container">
			<div class="pagination-info">
				显示 {{ (currentPage - 1) * pageSize + 1 }} 到 
				{{ Math.min(currentPage * pageSize, filteredTotal) }} 条，共 {{ filteredTotal }} 条
			</div>
			<el-pagination 
				background 
				layout="sizes, prev, pager, next, jumper, total" 
				:total="filteredTotal"
				:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:current-page="currentPage"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:disabled="tableLoading"
			/>
		</div>

		<!-- 新增表单对话框 -->
		<el-dialog
			title="新增员工"
			v-model="showAddForm"
			width="80%"
			:before-close="handleCloseAddForm"
		>
			<el-form 
				:model="formData" 
				ref="addFormRef"
				:rules="formRules"
				label-width="120px"
				class="add-form"
			>
				<!-- 第一行 -->
				<div class="form-row">
					<el-form-item label="姓名" prop="name">
						<el-input v-model="formData.name" placeholder="请输入员工姓名" />
					</el-form-item>
					
					<el-form-item label="手机号" prop="tel">
						<el-input v-model="formData.tel" type="number" placeholder="请输入手机号" />
					</el-form-item>
					
					<el-form-item label="身份证件号码" prop="IDnumber">
						<el-input 
							v-model="formData.IDnumber" 
							placeholder="请输入身份证号" 
							@blur="autoFillFromID"
						/>
					</el-form-item>
				</div>
				
				<!-- 第二行 -->
				<div class="form-row">
					<el-form-item label="性别" prop="gender">
						<el-select v-model="formData.gender" disabled placeholder="输入身份证号后自动填充">
							<el-option label="男" value="男" />
							<el-option label="女" value="女" />
						</el-select>
					</el-form-item>
					
					<el-form-item label="生日" prop="birthday">
						<el-date-picker disabled
							v-model="formData.birthday" 
							type="date" 
							placeholder="输入身份证号后自动填充" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
					
					<el-form-item label="籍贯" prop="address">
						<el-input v-model="formData.address" placeholder="请输入籍贯" />
					</el-form-item>
				</div>
				
				<!-- 第三行 -->
				<div class="form-row">
					<el-form-item label="岗位档级" prop="post_level">
						<el-tree-select
							v-model="formData.post_level"
							:data="treeLevelData"
							:render-after-expand="false"
							style="width: 100%"
							placeholder='请选择岗位档级'
							@change="autoFillSalaryAndGradeId"
						/>
					</el-form-item>
					
					<el-form-item label="岗位工资" prop="base_pay">
						<el-input v-model="formData.base_pay" disabled type="number" placeholder="输入档级后自动填充" />
					</el-form-item>
					
					<el-form-item label="学历" prop="record">
						<el-select v-model="formData.record" placeholder="请选择学历">
							<el-option v-for="edu in educationOptions" :key="edu" :label="edu" :value="edu" />
						</el-select>
					</el-form-item>
				</div>
				
				<!-- 第四行 -->
				<div class="form-row">
					<el-form-item label="开户行" prop="bank">
						<el-input v-model="formData.bank" placeholder="请输入开户行" />
					</el-form-item>
					
					<el-form-item label="银行卡号" prop="bank_card">
						<el-input v-model="formData.bank_card" type="number" placeholder="请输入银行卡号" />
					</el-form-item>
					
					<el-form-item label="政治面貌" prop="political_status">
						<el-select v-model="formData.political_status" placeholder="请选择政治面貌">
							<el-option v-for="status in politicsStatusOptions" :key="status" :label="status" :value="status" />
						</el-select>
					</el-form-item>
				</div>
				
				<!-- 第五行 -->
				<div class="form-row">
					<el-form-item label="公司" prop="company">
						<el-select v-model="formData.company" placeholder="请选择公司名称">
							<el-option 
								v-for="item in companyOptions" 
								:key="item.value" 
								:label="item.label" 
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					
					<el-form-item label="项目" prop="project">
						<el-select v-model="formData.project" placeholder="请选择项目名称">
							<el-option 
								v-for="item in projectOptions" 
								:key="item.value" 
								:label="item.label" 
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					
					<el-form-item label="用工形式" prop="layout">
						<el-select v-model="formData.layout" placeholder="请选择用工形式">
							<el-option label="长期派遣" value="1" />
							<el-option label="短期派遣" value="2" />
							<el-option label="学员" value="3" />
						</el-select>
					</el-form-item>
				</div>
				
				<!-- 第六行 -->
				<div class="form-row">
					<el-form-item label="员工状态" prop="status">
						<el-select v-model="formData.status" placeholder="请选择员工状态">
							<el-option label="在岗" value="1" />
							<el-option label="离职" value="2" />
						</el-select>
					</el-form-item>
					
					<el-form-item label="合同到期时间" prop="agreement_end">
						<el-date-picker 
							v-model="formData.agreement_end" 
							type="date" 
							placeholder="请选择合同到期时间" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
					
					<el-form-item label="现合同期限（年）" prop="agreement_num">
						<el-input v-model="formData.agreement_num" type="number" placeholder="请输入合同期限" />
					</el-form-item>
				</div>
				
				<!-- 第七行 -->
				<div class="form-row">
					<el-form-item label="入职时间" prop="entry_time">
						<el-date-picker 
							v-model="formData.entry_time" 
							type="date" 
							placeholder="请选择入职时间" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
					
					<el-form-item label="离职时间" prop="leave_time" v-if="formData.status === '2'">
						<el-date-picker 
							v-model="formData.leave_time" 
							type="date" 
							placeholder="请选择离职时间" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
				</div>
			</el-form>
			
			<template #footer>
				<el-button @click="handleCloseAddForm">取消</el-button>
				<el-button type="primary" @click="submitAddForm">确定</el-button>
			</template>
		</el-dialog>

		<!-- 编辑表单对话框 -->
		<el-dialog
			title="编辑员工"
			v-model="showEditForm"
			width="80%"
			:before-close="handleCloseEditForm"
		>
			<el-form 
				:model="editFormData" 
				ref="editFormRef"
				:rules="formRules"
				label-width="120px"
				class="add-form"
			>
				<!-- 第一行 -->
				<div class="form-row">
					<el-form-item label="姓名" prop="name">
						<el-input v-model="editFormData.name" placeholder="请输入员工姓名" />
					</el-form-item>
					
					<el-form-item label="手机号" prop="tel">
						<el-input v-model="editFormData.tel" type="number" placeholder="请输入手机号" />
					</el-form-item>
					
					<el-form-item label="身份证件号码" prop="IDnumber">
						<el-input 
							v-model="editFormData.IDnumber" 
							placeholder="请输入身份证号" 
							@blur="autoFillFromIDEdit"
						/>
					</el-form-item>
				</div>
				
				<!-- 第二行 -->
				<div class="form-row">
					<el-form-item label="性别" prop="gender">
						<el-select v-model="editFormData.gender" disabled placeholder="输入身份证号后自动填充">
							<el-option label="男" value="男" />
							<el-option label="女" value="女" />
						</el-select>
					</el-form-item>
					
					<el-form-item label="生日" prop="birthday">
						<el-date-picker disabled
							v-model="editFormData.birthday" 
							type="date" 
							placeholder="输入身份证号后自动填充" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
					
					<el-form-item label="籍贯" prop="address">
						<el-input v-model="editFormData.address" placeholder="请输入籍贯" />
					</el-form-item>
				</div>
				
				<!-- 第三行 -->
				<div class="form-row">
					<el-form-item label="岗位档级" prop="post_level">
						<el-tree-select
							v-model="editFormData.post_level"
							:data="treeLevelData"
							:render-after-expand="false"
							style="width: 100%"
							placeholder='请选择岗位档级'
							@change="autoFillSalaryAndGradeIdEdit"
						/>
					</el-form-item>
					
					<el-form-item label="岗位工资" prop="base_pay">
						<el-input v-model="editFormData.base_pay" disabled type="number" placeholder="输入档级后自动填充" />
					</el-form-item>
					
					<el-form-item label="学历" prop="record">
						<el-select v-model="editFormData.record" placeholder="请选择学历">
							<el-option v-for="edu in educationOptions" :key="edu" :label="edu" :value="edu" />
						</el-select>
					</el-form-item>
				</div>
				
				<!-- 第四行 -->
				<div class="form-row">
					<el-form-item label="开户行" prop="bank">
						<el-input v-model="editFormData.bank" placeholder="请输入开户行" />
					</el-form-item>
					
					<el-form-item label="银行卡号" prop="bank_card">
						<el-input v-model="editFormData.bank_card" type="number" placeholder="请输入银行卡号" />
					</el-form-item>
					
					<el-form-item label="政治面貌" prop="political_status">
						<el-select v-model="editFormData.political_status" placeholder="请选择政治面貌">
							<el-option v-for="status in politicsStatusOptions" :key="status" :label="status" :value="status" />
						</el-select>
					</el-form-item>
				</div>
				
				<!-- 第五行 -->
				<div class="form-row">
					<el-form-item label="公司" prop="company">
						<el-select v-model="editFormData.company" placeholder="请选择公司名称">
							<el-option 
								v-for="item in companyOptions" 
								:key="item.value" 
								:label="item.label" 
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					
					<el-form-item label="项目" prop="project">
						<el-select v-model="editFormData.project" placeholder="请选择项目名称">
							<el-option 
								v-for="item in projectOptions" 
								:key="item.value" 
								:label="item.label" 
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					
					<el-form-item label="用工形式" prop="layout">
						<el-select v-model="editFormData.layout" placeholder="请选择用工形式">
							<el-option label="长期派遣" value="1" />
							<el-option label="短期派遣" value="2" />
							<el-option label="学员" value="3" />
						</el-select>
					</el-form-item>
				</div>
				
				<!-- 第六行 -->
				<div class="form-row">
					<el-form-item label="员工状态" prop="status">
						<el-select v-model="editFormData.status" placeholder="请选择员工状态">
							<el-option label="在岗" value="1" />
							<el-option label="离职" value="2" />
						</el-select>
					</el-form-item>
					
					<el-form-item label="合同到期时间" prop="agreement_end">
						<el-date-picker 
							v-model="editFormData.agreement_end" 
							type="date" 
							placeholder="请选择合同到期时间" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
					
					<el-form-item label="现合同期限（年）" prop="agreement_num">
						<el-input v-model="editFormData.agreement_num" type="number" placeholder="请输入合同期限" />
					</el-form-item>
				</div>
				
				<!-- 第七行 -->
				<div class="form-row">
					<el-form-item label="入职时间" prop="entry_time">
						<el-date-picker 
							v-model="editFormData.entry_time" 
							type="date" 
							placeholder="请选择入职时间" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
					
					<el-form-item label="离职时间" prop="leave_time" v-if="editFormData.status === '2'">
						<el-date-picker 
							v-model="editFormData.leave_time" 
							type="date" 
							placeholder="请选择离职时间" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
				</div>
			</el-form>
			
			<template #footer>
				<el-button @click="handleCloseEditForm">取消</el-button>
				<el-button type="primary" @click="submitEditForm">确定</el-button>
			</template>
		</el-dialog>

		<!-- 员工详情抽屉 - 优化版 -->
		<el-drawer
			v-model="employeeDrawerVisible"
			direction="rtl"
			size="70%"
			class="custom-drawer"
		>
			<template #header>
				<div class="drawer-header">
					<h2>{{ selectedEmployee?.name }}</h2>
					
				</div>
			</template>
			
			<el-tabs v-model="activeTab" type="card">
				<el-tab-pane label="基本信息" name="basic">
          <div style="display: flex; justify-content:space-between;">
            <p>岗位信息</p>
            <el-button 
						type="text" 
						@click="openEditForm"
						class="edit-button"
					>
						编辑
					</el-button>
          </div>
					<!-- 基本信息使用与新增表单相同的布局，但设置为禁用 -->
					<el-form 
						:model="viewFormData" 
						label-width="120px"
						class="add-form"
					>
						<!-- 第一行 -->
						<div class="form-row">
							<el-form-item label="姓名">
								<el-input v-model="viewFormData.name" disabled />
							</el-form-item>
							
							<el-form-item label="手机号">
								<el-input v-model="viewFormData.tel" disabled />
							</el-form-item>
							
							<el-form-item label="身份证件号码">
								<el-input v-model="viewFormData.IDnumber" disabled />
							</el-form-item>
						</div>
						
						<!-- 第二行 -->
						<div class="form-row">
							<el-form-item label="性别">
								<el-select v-model="viewFormData.gender" disabled>
									<el-option label="男" value="男" />
									<el-option label="女" value="女" />
								</el-select>
							</el-form-item>
							
							<el-form-item label="生日">
								<el-date-picker 
									v-model="viewFormData.birthday" 
									type="date" 
									disabled
									value-format="YYYY-MM-DD"
								/>
							</el-form-item>
							
							<el-form-item label="籍贯">
								<el-input v-model="viewFormData.address" disabled />
							</el-form-item>
						</div>
						
						<!-- 第三行 -->
						<div class="form-row">
							<el-form-item label="岗位档级">
								<el-tree-select
									v-model="viewFormData.post_level"
									:data="treeLevelData"
									:render-after-expand="false"
									style="width: 100%"
									placeholder='请选择岗位档级'
									disabled
								/>
							</el-form-item>
							
							<el-form-item label="岗位工资">
								<el-input v-model="viewFormData.base_pay" disabled />
							</el-form-item>
							
							<el-form-item label="学历">
								<el-select v-model="viewFormData.record" disabled>
									<el-option v-for="edu in educationOptions" :key="edu" :label="edu" :value="edu" />
								</el-select>
							</el-form-item>
						</div>
						
						<!-- 第四行 -->
						<div class="form-row">
							<el-form-item label="开户行">
								<el-input v-model="viewFormData.bank" disabled />
							</el-form-item>
							
							<el-form-item label="银行卡号">
								<el-input v-model="viewFormData.bank_card" disabled />
							</el-form-item>
							
							<el-form-item label="政治面貌">
								<el-select v-model="viewFormData.political_status" disabled>
									<el-option v-for="status in politicsStatusOptions" :key="status" :label="status" :value="status" />
								</el-select>
							</el-form-item>
						</div>
						
						<!-- 第五行 -->
						<div class="form-row">
							<el-form-item label="公司">
								<el-select v-model="viewFormData.company" disabled>
									<el-option 
										v-for="item in companyOptions" 
										:key="item.value" 
										:label="item.label" 
										:value="item.value"
									/>
								</el-select>
							</el-form-item>
							
							<el-form-item label="项目">
								<el-select v-model="viewFormData.project" disabled>
									<el-option 
										v-for="item in projectOptions" 
										:key="item.value" 
										:label="item.label" 
										:value="item.value"
									/>
								</el-select>
							</el-form-item>
							
							<el-form-item label="用工形式">
								<el-select v-model="viewFormData.layout" disabled>
									<el-option label="长期派遣" value="1" />
									<el-option label="短期派遣" value="2" />
									<el-option label="学员" value="3" />
								</el-select>
							</el-form-item>
						</div>
						
						<!-- 第六行 -->
						<div class="form-row">
							<el-form-item label="员工状态">
								<el-select v-model="viewFormData.status" disabled>
									<el-option label="在岗" value="1" />
									<el-option label="离职" value="2" />
								</el-select>
							</el-form-item>
							
							<el-form-item label="合同到期时间">
								<el-date-picker 
									v-model="viewFormData.agreement_end" 
									type="date" 
									disabled
									value-format="YYYY-MM-DD"
								/>
							</el-form-item>
							
							<el-form-item label="现合同期限（年）">
								<el-input v-model="viewFormData.agreement_num" disabled />
							</el-form-item>
						</div>
						
						<!-- 第七行 -->
						<div class="form-row">
							<el-form-item label="入职时间">
								<el-date-picker 
									v-model="viewFormData.entry_time" 
									type="date" 
									disabled
									value-format="YYYY-MM-DD"
								/>
							</el-form-item>
							
							<el-form-item label="离职时间" v-if="viewFormData.status === '2'">
								<el-date-picker 
									v-model="viewFormData.leave_time" 
									type="date" 
									disabled
									value-format="YYYY-MM-DD"
								/>
							</el-form-item>
						</div>
					</el-form>
				</el-tab-pane>
				
				<el-tab-pane label="员工合同" name="contract">
					<div class="tab-content">
              <div>
                  操作说明：</div>
                  <div>1、点击新增创建合同</div>
                  <div>2、点击编辑修改合同</div>
                  <div>2、点击签署，发起合同签章，甲乙双方根据收到的短信链接点击后进行签署</div>
                <div>3、甲乙双方签署成功后，点击归档，合同签署流程结束</div>
                <div style="margin-bottom: 20px;">4、乙方尚未签署时，甲方可撤回修改重新发起签署</div>
						<el-button 
					color="#0052CC" 
					@click="openAddContractForm"
					:disabled="isAdding"
          style="margin-bottom: 20px;"
				>
					新增
				</el-button>
         <el-table :data="tableData" style="width: 100%">
    <el-table-column fixed prop="date" label="合同名称"/>
    <el-table-column prop="name" label="乙方姓名" />
    <el-table-column prop="state" label="合同类型" />
    <el-table-column prop="city" label="合同开始时间" />
    <el-table-column prop="address" label="合同结束时间"/>
    <el-table-column prop="zip" label="合同状态" />
    <el-table-column fixed="right" label="操作" width="180">
      <template #default >
        <el-button type="primary" size="small" @click="handleClick"
          >签署</el-button
        >
        <el-button type="danger" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
						
					</div>
				</el-tab-pane>
				
				<el-tab-pane label="工资社保" name="salary">
					<div class="tab-content">
						<el-date-picker
          v-model="value2"
          type="month"
          placeholder="请选择批次时间"
        />
        <el-table :data="tableData" style="width: 100%;margin-top:20px">
    <el-table-column fixed prop="date" label="序号" width="120" />
    <el-table-column fixed prop="date" label="姓名" width="120" />
    <el-table-column prop="date" label="工资所属日期" width="120" />
    <el-table-column prop="date" label="用工形式" width="120" />
    <el-table-column prop="date" label="职务" />
    <el-table-column prop="date" label="薪水等级" width="120" />
    <el-table-column label="薪资待遇标准" width="120">
      <el-table-column prop="name" label="岗位工资" width="120"/>
      <el-table-column prop="name" label="安全质量奖金" width="120" />
      <el-table-column prop="name" label="岗位津贴" width="120" />
      <el-table-column prop="name" label="绩效奖金" width="120" />
    </el-table-column>
    <el-table-column prop="date" label="应出勤天数" width="120" />
    <el-table-column prop="date" label="实际出勤天数" width="120" />
    <el-table-column prop="date" label="岗位工资" width="120" />
    <el-table-column prop="date" label="安全质量奖金" width="120"/>
    <el-table-column prop="date" label="岗位津贴" width="120" />
    <el-table-column prop="date" label="证书补贴" width="120" />
    <el-table-column prop="date" label="通讯补贴" width="120" />
    <el-table-column prop="date" label="电脑补贴" width="120" />
    <el-table-column prop="date" label="夜班补贴" width="120" />
    <el-table-column prop="date" label="加班补贴" width="120" />
    <el-table-column prop="date" label="误餐补贴" width="120" />
    <el-table-column prop="date" label="租房补贴" width="120" />
    <el-table-column prop="date" label="高温补贴" width="120" />
    <el-table-column prop="date" label="取暖补贴" width="120" />
    <el-table-column prop="date" label="外出施工补贴" width="120" />
    <el-table-column prop="date" label="奖金" />
    <el-table-column prop="date" label="其他补助" width="120" />
    <el-table-column prop="date" label="扣款" />
    <el-table-column prop="date" label="应发小计" width="120" />
    <el-table-column prop="date" label="个人社保" width="120" />
    <el-table-column prop="date" label="个税" />
    <el-table-column prop="date" label="实发小计" width="120" />
    <el-table-column prop="date" label="单位社保" width="120" />
    <el-table-column prop="date" label="管理费" width="120" />
    <el-table-column prop="date" label="电话" />
    <el-table-column prop="date" label="身份证号" width="150" />
    <el-table-column prop="date" label="银行卡" width="140" />
    <el-table-column prop="date" label="审计批次" width="120" />
    <el-table-column fixed="right" prop="date" label="合计金额" width="120" />
  </el-table>
					</div>
				</el-tab-pane>
				
					<el-tab-pane label="证书列表" name="certificates">
					<div class="tab-content">
            <div class="certificate-cards-container">
              <div 
                v-for="cert in certificateTypes" 
                :key="cert.value" 
                class="certificate-card"
                @click="openAddCertificateForm(cert)"
              >
                <div class="certificate-name">{{ cert.label }}</div>
              </div>
            </div>
					</div>
				</el-tab-pane>
			</el-tabs>

      <!-- 新增证书弹窗 -->
<el-dialog
  title="新增证书"
  v-model="showAddCertificateForm"
  width="50%"
  :before-close="handleCloseAddCertificateForm"
>
  <el-form 
    :model="certificateFormData" 
    ref="certificateFormRef"
    label-width="120px"
    class="add-form"
  >
   <el-form-item label="证书名称" prop="name">
      <el-input v-model="certificateFormData.name" style="width: 100%" />
    </el-form-item>
    
    <el-form-item label="证书等级" prop="level">
      <el-input v-model="certificateFormData.level" placeholder="请输入证书等级" style="width: 100%" />
    </el-form-item>
    
    <el-form-item label="获取时间" prop="issueDate">
      <el-date-picker 
        v-model="certificateFormData.issueDate" 
        type="date" 
        placeholder="请选择获取时间" 
        value-format="YYYY-MM-DD"
        style="width: 100%"
      />
    </el-form-item>
    
    <el-form-item label="复审时间" prop="reviewDate">
      <el-date-picker 
        v-model="certificateFormData.reviewDate" 
        type="date" 
        placeholder="请选择复审时间" 
        value-format="YYYY-MM-DD"
        style="width: 100%"
      />
    </el-form-item>
    
    <!-- 文件上传 -->
    <el-form-item label="证书图片" prop="image">
      <el-upload
        class="upload-demo"
        action="/api/upload"
        :on-success="handleCertificateUploadSuccess"
        :on-error="handleCertificateUploadError"
        :file-list="fileList"
        accept=".jpg,.jpeg,.png,.pdf"
        :limit="1"
        :on-exceed="handleCertificateExceed"
        list-type="picture"
      >
        <el-button type="primary">点击上传</el-button>
        <template #tip>
          <div class="el-upload__tip">
            只能上传jpg、jpeg、png、pdf文件，且不超过10MB
          </div>
        </template>
      </el-upload>
    </el-form-item>
  </el-form>
  
  <template #footer>
    <el-button type="danger" @click="deleteCertificate">删除证书</el-button>
    <el-button type="primary" @click="submitCertificateForm">确认</el-button>
  </template>
</el-dialog>
			
			<template #footer>
				<el-button @click="employeeDrawerVisible = false">关闭</el-button>
			</template>
		</el-drawer>

		<!-- 员工合同新增弹窗 -->
		<el-dialog
			title="新增合同"
			v-model="showAddContractForm"
			width="70%"
			:before-close="handleCloseAddContractForm"
		>
			<el-form 
				:model="contractFormData" 
				ref="contractFormRef"
				:rules="contractFormRules"
				label-width="120px"
				class="add-form"
			>
				<!-- 第一行 -->
				<div class="form-row">
					<el-form-item label="合同名称" prop="contractName">
						<el-input v-model="contractFormData.contractName" placeholder="请输入合同名称" />
					</el-form-item>
					
					<el-form-item label="合同类型" prop="contractType">
						<el-select v-model="contractFormData.contractType" placeholder="请选择合同类型">
							<el-option label="劳务合同" value="1" />
							<el-option label="就业合同" value="2" />
							<el-option label="租赁合同" value="3" />
							<el-option label="合作协议" value="4" />
						</el-select>
					</el-form-item>
					
					<el-form-item label="合同编号" prop="contractNumber">
						<el-input v-model="contractFormData.contractNumber" placeholder="请输入合同编号" />
					</el-form-item>
				</div>
				
				<!-- 第二行 -->
				<div class="form-row">
					<el-form-item label="甲方姓名" prop="partyAName">
						<el-input v-model="contractFormData.partyAName" placeholder="请输入甲方姓名" />
					</el-form-item>
					
					<el-form-item label="甲方身份证号" prop="partyAIdCard">
						<el-input v-model="contractFormData.partyAIdCard" placeholder="请输入甲方身份证号" />
					</el-form-item>
					
					<el-form-item label="甲方手机号" prop="partyAPhone">
						<el-input v-model="contractFormData.partyAPhone" type="number" placeholder="请输入甲方手机号" />
					</el-form-item>
				</div>
				
				<!-- 第三行 -->
				<div class="form-row">
					<el-form-item label="甲方公司全称" prop="partyACompany">
						<el-input v-model="contractFormData.partyACompany" placeholder="请输入甲方公司全称" />
					</el-form-item>
					
					<el-form-item label="甲方机构代码" prop="partyAOrgCode">
						<el-input v-model="contractFormData.partyAOrgCode" placeholder="请输入甲方机构代码" />
					</el-form-item>
					
					<el-form-item label="乙方姓名" prop="partyBName">
						<el-input v-model="contractFormData.partyBName" placeholder="乙方姓名" disabled />
					</el-form-item>
				</div>
				
				<!-- 第四行 -->
				<div class="form-row">
					<el-form-item label="乙方身份证号" prop="partyBIdCard">
						<el-input v-model="contractFormData.partyBIdCard" placeholder="乙方身份证号" disabled />
					</el-form-item>
					
					<el-form-item label="乙方手机号" prop="partyBPhone">
						<el-input v-model="contractFormData.partyBPhone" placeholder="乙方手机号" disabled />
					</el-form-item>
					
					<el-form-item label="执行状态" prop="executionStatus">
						<el-select v-model="contractFormData.executionStatus" placeholder="请选择执行状态">
							<el-option label="执行中" value="1" />
							<el-option label="已到期" value="2" />
						</el-select>
					</el-form-item>
				</div>
				
				<!-- 第五行 -->
				<div class="form-row">
					<el-form-item label="开始时间" prop="startDate">
						<el-date-picker 
							v-model="contractFormData.startDate" 
							type="date" 
							placeholder="请选择开始时间" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
					
					<el-form-item label="结束时间" prop="endDate">
						<el-date-picker 
							v-model="contractFormData.endDate" 
							type="date" 
							placeholder="请选择结束时间" 
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
				</div>
				
				<!-- 文件上传 -->
				<el-form-item label="合同文件" prop="contractFile">
					<el-upload
						class="upload-demo"
						action="/api/upload"
						:file-list="fileList"
						accept=".pdf,.doc,.docx"
						:limit="1"
					>
						<el-button type="primary">点击上传</el-button>
						<template #tip>
							<div class="el-upload__tip">
								只能上传PDF、Word文件，且不超过20MB
							</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			
			<template #footer>
				<el-button @click="handleCloseAddContractForm">取消</el-button>
				<el-button type="primary" @click="submitAddContractForm">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, nextTick, watch, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ElTable, ElMessageBox, ElMessage, ElForm, ElFormItem, ElTag, ElEmpty, ElTabs, ElTabPane, ElDescriptions, ElUpload, ElButton, ElDialog } from 'element-plus'
import { getRoleList, getTableList, addstaff, getLevelList } from '../../api/staff/index.js';
import { editstaff,getCertList,addCert,delCert,getContractList,addContract } from '../../api/staff/index.js';
import { getOrgTree } from '../../api/account/index.js';

// 定义API返回的员工数据结构接口
interface Employee {
  id: number;
  name: string;
  base_pay: number;
  grade_title: string;
  birthday: string;
  tel: string;
  idcard: string;
  title: string;
  account: string;
  political_status: string;
  address: string;
  record: string;
  create_time: string;
  status: string;
  layout: string;
  start_time: string;
  time_section: string;
  end_time: string;
  agreement_num: number;
  bank_card: string;
  bank: string;
  sex?: string;
  // 新增字段用于编辑表单
  companyid?: string;
  projectid?: string;
  gradeid?: number;
  agreement_end?: string;
  entry_time?: string;
  leave_time?: string;
}

// 定义树形结构接口 - 适配el-tree-select组件
interface TreeData {
  id: number;
  label: string;
  value: string;
  children?: TreeData[];
  // 档级特有属性
  salary?: number;
  gradeid?: number;
}

// 搜索表单数据
const searchForm = reactive({
  name: '',
  company: '',
  project: '',
  level: '',
  certificate: '',
  month: '',
  typeFilter: ''
})

// 分页相关变量
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const filteredTotal = ref(0)
const tableLoading = ref(false)
const allEmployees = ref<Employee[]>([]);
const tableRef = ref<InstanceType<typeof ElTable>>()

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: NodeJS.Timeout | null = null;
  return (...args: any[]) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
};

// 搜索处理（带防抖）
const handleSearch = debounce(() => {
  currentPage.value = 1;
  fetchTableData(1, pageSize.value);
}, 300);


// 监听搜索条件变化
watch(
  () => [
    searchForm.name, 
    searchForm.company, 
    searchForm.level, 
    searchForm.month, 
    searchForm.project, 
    searchForm.certificate,
    searchForm.typeFilter
  ],
  () => handleSearch()
)
// 员工抽屉相关
const employeeDrawerVisible = ref(false)
const selectedEmployee = ref<Employee | null>(null)
const activeTab = ref('basic')
const showEditForm = ref(false)

// 档级相关数据
const rawLevelData = ref<any[]>([]) // 原始档级数据
const treeLevelData = ref<TreeData[]>([]) // 转换后的树形结构数据

// 递归转换数据为树形结构 - 适配el-tree-select
const convertToTree = (data: any[], parentId: number | null = 0): TreeData[] => {
  return data
    .filter(item => item.pid === (parentId || 0))
    .map(item => {
      // 递归查找子节点
      const children = convertToTree(data, item.id);
      
      return {
        id: item.id,
        label: item.title,
        value: String(item.id),
        salary: parseFloat(item.money) || 0,
        gradeid: item.id,
        // 只有存在子节点时才添加children属性
        ...(children.length > 0 && { children })
      };
    });
};

// 过滤后的员工列表
const filteredEmployees = computed(() => {
  return allEmployees.value.filter(emp => {
    // 姓名过滤
    const nameMatch = !searchForm.name || 
      (emp.name && emp.name.toLowerCase().includes(searchForm.name.toLowerCase()));
    
    // 公司过滤 - 根据公司名称进行过滤
    let companyMatch = true;
    if (searchForm.company) {
      // 获取选中公司的名称
      const selectedCompany = companyOptions.value.find(
        (company) => company.value === searchForm.company
      );
      
      // 根据公司名称进行过滤
      companyMatch = selectedCompany ? !!(emp.account && emp.account.includes(selectedCompany.label)) : false;
    }

    // 项目过滤
    const projectMatch = !searchForm.project || 
      (emp.title && emp.title.toLowerCase().includes(searchForm.project.toLowerCase()));
      
    // 档级过滤 - 改进匹配逻辑
    const levelMatch = !searchForm.level || 
      (emp.grade_title && emp.grade_title.toString() === searchForm.level) ||
      (emp.gradeid && emp.gradeid.toString() === searchForm.level);
      
    // 证书过滤
    const certificateMatch = !searchForm.certificate || 
      // 这里需要根据实际证书数据结构进行调整
      true; // 临时返回true，实际应根据证书数据过滤
      
    // 月份过滤
    const monthMatch = !searchForm.month || 
      (emp.create_time && emp.create_time.includes(dayjs(searchForm.month).format('YYYY-MM')));
      
    // 按钮筛选条件
    let typeMatch = true;
    switch(searchForm.typeFilter) {
      case 'entry':
        typeMatch = emp.status === '在岗' || emp.status === '1';
        break;
      case 'leave':
        typeMatch = emp.status === '离职' || emp.status === '2';
        break;
      case 'long-term':
        typeMatch = emp.layout === '长期派遣' || emp.layout === '1';
        break;
      case 'short-term':
        typeMatch = emp.layout === '短期派遣' || emp.layout === '2';
        break;
      case 'trainee':
        typeMatch = emp.layout === '学员' || emp.layout === '3';
        break;
      case 'duplicate':
        if (emp.idcard) {
          const sameIdCards = allEmployees.value.filter(e => e.idcard === emp.idcard);
          typeMatch = sameIdCards.length > 1;
        } else {
          typeMatch = false;
        }
        break;
      default:
        typeMatch = true;
    }
      
    return nameMatch && companyMatch && projectMatch && levelMatch && certificateMatch && monthMatch && typeMatch;
  });
});
// 当前页数据
const pagedEmployees = computed(() => {
  filteredTotal.value = filteredEmployees.value.length;
  
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filteredEmployees.value.slice(startIndex, endIndex);
});

// 获取表格数据
const fetchTableData = async (page: number = 1, size: number = 10) => {
  if (tableLoading.value) return;
  
  tableLoading.value = true;
  try {
    const res = await getTableList({
      page,
      size,
      name: searchForm.name || undefined,
      company: searchForm.company || undefined,
      project: searchForm.project || undefined,
      level: searchForm.level || undefined,
      certificate: searchForm.certificate || undefined,
      month: searchForm.month ? dayjs(searchForm.month).format('YYYY-MM') : undefined,
      status: searchForm.typeFilter === 'entry' ? '1' : 
              searchForm.typeFilter === 'leave' ? '2' : 
              searchForm.typeFilter === 'long-term' ? '1' : 
              searchForm.typeFilter === 'short-term' ? '2' : 
              searchForm.typeFilter === 'trainee' ? '3' : undefined,
      layout: searchForm.typeFilter === 'long-term' ? '1' : 
              searchForm.typeFilter === 'short-term' ? '2' : 
              searchForm.typeFilter === 'trainee' ? '3' : undefined
    });
    
    allEmployees.value = res.data || [];
    totalItems.value = res.total || 0;
  } catch (error) {
    console.error('获取表格数据失败:', error);
    ElMessage.error('获取数据失败，请重试');
  } finally {
    tableLoading.value = false;
  }
}

// 处理分页变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchTableData(1, size);
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  fetchTableData(page, pageSize.value);
}

// 按钮筛选处理
const filterByType = (type: string) => {
  searchForm.typeFilter = type;
  currentPage.value = 1;
  fetchTableData(1, pageSize.value);
  highlightActiveButton(type);
}

// 高亮当前选中的筛选按钮
const highlightActiveButton = (type: string) => {
  document.querySelectorAll('.staff_function .el-button').forEach(btn => {
    btn.classList.remove('active-filter-btn');
  });
  
  const buttons = document.querySelectorAll('.staff_function .el-button');
  switch(type) {
    case 'entry':
      buttons[0]?.classList.add('active-filter-btn');
      break;
    case 'leave':
      buttons[1]?.classList.add('active-filter-btn');
      break;
    case 'long-term':
      buttons[2]?.classList.add('active-filter-btn');
      break;
    case 'short-term':
      buttons[3]?.classList.add('active-filter-btn');
      break;
    case 'trainee':
      buttons[4]?.classList.add('active-filter-btn');
      break;
    case 'duplicate':
      buttons[5]?.classList.add('active-filter-btn');
      break;
  }
}

// 打开员工详情抽屉
const openEmployeeDrawer = (employee: Employee) => {
  selectedEmployee.value = employee;
  // 填充查看表单数据
  fillViewFormData(employee);
  employeeDrawerVisible.value = true;
}

// 填充查看表单数据
const fillViewFormData = (employee: Employee) => {
  viewFormData.name = employee.name || '';
  viewFormData.tel = employee.tel || '';
  viewFormData.IDnumber = employee.idcard || '';
  viewFormData.gender = employee.sex || '';
  viewFormData.birthday = employee.birthday || '';
  viewFormData.address = employee.address || '';
  viewFormData.post_level_label = employee.grade_title || '';
  viewFormData.post_level = employee.gradeid ? String(employee.gradeid) : ''; // 添加这一行
  viewFormData.base_pay = employee.base_pay || 0;
  viewFormData.record = employee.record || '';
  viewFormData.bank = employee.bank || '';
  viewFormData.bank_card = employee.bank_card || '';
  viewFormData.political_status = employee.political_status || '';
  
  // 公司回显 - 根据ID查找公司名称
  if (employee.companyid) {
    viewFormData.company = String(employee.companyid);
  } else {
    viewFormData.company = '';
  }
  
  // 项目回显 - 根据ID查找项目名称
  if (employee.projectid) {
    viewFormData.project = String(employee.projectid);
  } else {
    viewFormData.project = '';
  }
  
  // 用工形式回显 (1 长期派遣，2 短期派遣，3 学员)
  viewFormData.layout = employee.layout ? String(employee.layout) : '';
  
  // 员工状态回显 (1 在岗，2 离职)
  viewFormData.status = employee.status ? String(employee.status) : '';
  
  viewFormData.agreement_end = employee.agreement_end || '';
  viewFormData.agreement_num = employee.agreement_num || 0;
  viewFormData.entry_time = employee.start_time || '';
  viewFormData.leave_time = employee.end_time || '';
}

// 打开编辑表单
const openEditForm = () => {
  if (!selectedEmployee.value) return;
  
  // 填充编辑表单数据
  fillEditFormData(selectedEmployee.value);
  showEditForm.value = true;
}

// 填充编辑表单数据
const fillEditFormData = (employee: Employee) => {
  editFormData.id = employee.id;
  editFormData.name = employee.name || '';
  editFormData.tel = employee.tel || '';
  editFormData.IDnumber = employee.idcard || '';
  editFormData.gender = employee.sex || '';
  editFormData.birthday = employee.birthday || '';
  editFormData.address = employee.address || '';
  editFormData.post_level = employee.gradeid ? String(employee.gradeid) : ''; // 根据gradeid设置岗位档级
  editFormData.gradeid = employee.gradeid || 0;
  editFormData.base_pay = employee.base_pay || 0;
  editFormData.record = employee.record || '';
  editFormData.bank = employee.bank || '';
  editFormData.bank_card = employee.bank_card || '';
  editFormData.political_status = employee.political_status || '';
  
  // 公司回显 - 根据ID查找公司名称
  if (employee.companyid) {
    editFormData.company = String(employee.companyid);
  } else {
    editFormData.company = '';
  }
  
  // 项目回显 - 根据ID查找项目名称
  if (employee.projectid) {
    editFormData.project = String(employee.projectid);
  } else {
    editFormData.project = '';
  }
  
  // 用工形式回显 (1 长期派遣，2 短期派遣，3 学员)
  // 直接使用原始值，因为el-select组件需要的是value而不是显示的文本
  editFormData.layout = employee.layout ? String(employee.layout) : '';
  
  // 员工状态回显 (1 在岗，2 离职)
  // 直接使用原始值，因为el-select组件需要的是value而不是显示的文本
  editFormData.status = employee.status ? String(employee.status) : '';
  
  editFormData.agreement_end = employee.agreement_end || '';
  editFormData.agreement_num = employee.agreement_num || 0;
  editFormData.entry_time = employee.start_time || '';
  editFormData.leave_time = employee.end_time || '';
  
  // 如果有gradeid但没有base_pay，尝试从树形数据中查找对应的薪资
  if (employee.gradeid && !employee.base_pay) {
    const findLevelData = (tree: TreeData[], id: number): TreeData | null => {
      for (const node of tree) {
        if (node.id === id) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = findLevelData(node.children, id);
          if (found) return found;
        }
      }
      return null;
    };
    
    const selectedLevel = findLevelData(treeLevelData.value, employee.gradeid);
    if (selectedLevel) {
      editFormData.base_pay = selectedLevel.salary || 0;
    }
  }
}

// 获取用工形式文本
const getLayoutText = (layout: string) => {
  switch(layout) {
    case '1': return '长期派遣';
    case '2': return '短期派遣';
    case '3': return '学员';
    default: return layout;
  }
}

// 获取员工状态文本
const getStatusText = (status: string) => {
  switch(status) {
    case '1': return '在岗';
    case '2': return '离职';
    default: return status;
  }
}

// 获取合同类型文本
const getContractTypeText = (type: string) => {
  switch(type) {
    case '1': return '劳务合同';
    case '2': return '就业合同';
    case '3': return '租赁合同';
    case '4': return '合作协议';
    default: return '未知类型';
  }
}

// 检查证书是否有效
const isCertificateValid = (expiryDate: string) => {
  return dayjs(expiryDate).isAfter(dayjs());
}

// 下拉选项数据
interface SelectOption {
  value: string;
  label: string;
}

interface PostLevelOption extends SelectOption {
  salary: number;
  gradeid: number;
}

interface CertificateOption extends SelectOption {}

const companyOptions = ref<SelectOption[]>([])
const projectOptions = ref<SelectOption[]>([])
const certificateOptions: CertificateOption[] = [
  { value: '1', label: '毕业证' },
  { value: '2', label: '电工证lsq' },
  { value: '3', label: '驾驶证' },
  { value: '4', label: '荣誉证' },
  { value: '4', label: '技工证' },
  { value: '4', label: '学位证' }
]

// 添加公司选项过滤相关数据
const filteredCompanyOptions = ref<SelectOption[]>([])
const companyLoading = ref(false)

// 表单相关选项
const postLevelOptions = ref<PostLevelOption[]>([])
const politicsStatusOptions = ['党员', '团员', '群众']
const educationOptions = ['初中及以下','高中', '大专', '本科', '研究生', '博士']

// 工资条模拟数据
const salaryRecords = ref([
  { month: '2023-06', baseSalary: 5000, positionSalary: 3000, performance: 1000, bonus: 500, deduction: 200, total: 9300 },
  { month: '2023-05', baseSalary: 5000, positionSalary: 3000, performance: 800, bonus: 0, deduction: 150, total: 8650 },
  { month: '2023-04', baseSalary: 5000, positionSalary: 3000, performance: 1200, bonus: 1000, deduction: 100, total: 10100 }
])

// 证书模拟数据
const certificates = ref([
  { name: '一级建造师证书', number: 'JZ00123456', issueDate: '2020-05-15', expiryDate: '2026-05-14' },
  { name: '注册安全工程师', number: 'AQ00987654', issueDate: '2021-08-20', expiryDate: '2024-08-19' },
  { name: 'BIM工程师', number: 'BIM567890', issueDate: '2022-03-10', expiryDate: '2025-03-09' }
])

// 合同数据

// 合同表格模拟数据
const tableData = ref([
  {
    date: '劳动合同',
    name: '张三',
    state: '固定期限',
    city: '2023-01-01',
    address: '2025-12-31',
    zip: '已签署'
  }
])

// 新增表单数据
const formData = reactive({
  name: '',
  tel: '',
  IDnumber: '',
  gender: '',
  birthday: '',
  address: '',
  post_level: '',
  gradeid: 0,
  base_pay: 0,
  record: '',
  bank: '',
  bank_card: '',
  political_status: '',
  company: '',
  project: '',
  layout: '',
  status: '1',
  agreement_end: '',
  agreement_num: 0,
  entry_time: '',
  leave_time: ''
})

// 编辑表单数据
const editFormData = reactive({
  id: 0,
  name: '',
  tel: '',
  IDnumber: '',
  gender: '',
  birthday: '',
  address: '',
  post_level: '',
  gradeid: 0,
  base_pay: 0,
  record: '',
  bank: '',
  bank_card: '',
  political_status: '',
  company: '',
  project: '',
  layout: '',
  status: '1',
  agreement_end: '',
  agreement_num: 0,
  entry_time: '',
  leave_time: ''
})

// 查看表单数据（基本信息展示用）
const viewFormData = reactive({
  name: '',
  tel: '',
  IDnumber: '',
  gender: '',
  birthday: '',
  address: '',
  post_level_label: '', // 展示用的档级名称
  post_level: '', // 实际值
  gradeid: 0,
  base_pay: 0,
  record: '',
  bank: '',
  bank_card: '',
  political_status: '',
  company: '',
  project: '',
  layout: '',
  status: '1',
  agreement_end: '',
  agreement_num: 0,
  entry_time: '',
  leave_time: ''
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  tel: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  IDnumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号格式', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthday: [
    { required: true, message: '请选择生日', trigger: 'change' }
  ],
  post_level: [
    { required: true, message: '请选择岗位档级', trigger: 'change' }
  ],
  base_pay: [
    { required: true, message: '请输入岗位工资', trigger: 'blur' }
  ],
  record: [
    { required: true, message: '请选择学历', trigger: 'change' }
  ],
  company: [
    { required: true, message: '请选择公司名称', trigger: 'change' }
  ],
  project: [
    { required: true, message: '请选择项目名称', trigger: 'change' }
  ],
  layout: [
    { required: true, message: '请选择用工形式', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择员工状态', trigger: 'change' }
  ],
  entry_time: [
    { required: true, message: '请选择入职时间', trigger: 'change' }
  ],
  agreement_num: [
    { required: true, message: '请输入合同期限', trigger: 'blur' }
  ],
  agreement_end: [
    { required: true, message: '请选择合同到期时间', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入籍贯', trigger: 'blur' }
  ],
  bank: [
    { required: true, message: '请输入开户行', trigger: 'blur' }
  ],
  bank_card: [
    { required: true, message: '请输入银行卡号', trigger: 'blur' }
  ],
  political_status: [
    { required: true, message: '请选择政治面貌', trigger: 'change' }
  ],
  leave_time: [
    { required: true, message: '请选择离职时间', trigger: 'change' }
  ]
})

// 表单引用
const addFormRef = ref<InstanceType<typeof ElForm>>()
const editFormRef = ref<InstanceType<typeof ElForm>>()

// 状态管理
const state = reactive({
  selectedRows: [] as Employee[],
  isAdding: false,
  loadingIds: [] as number[],
  showAddForm: false
})

const { selectedRows, isAdding, loadingIds, showAddForm } = toRefs(state)

// 处理选择变化
const handleSelectionChange = (val: Employee[]) => {
  selectedRows.value = val
}

// 切换选择状态
const toggleSelection = (rows?: Employee[]) => {
  nextTick(() => {
    if (rows) {
      rows.forEach(row => {
        tableRef.value?.toggleRowSelection(row, true)
      })
    } else {
      const isAllSelected = selectedRows.value.length === pagedEmployees.value.length
      pagedEmployees.value.forEach(row => {
        tableRef.value?.toggleRowSelection(row, !isAllSelected)
      })
    }
  })
}

// 删除单行
const deleteRow = async (row: Employee) => {
  try {
    await ElMessageBox.confirm('确定要删除该员工信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 显示加载状态
    loadingIds.value.push(row.id)
    
    // 调用API删除（实际项目中取消注释）
    // await deleteEmployee(row.id)
    
    // 重新获取数据
    await fetchTableData(currentPage.value, pageSize.value)
    
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    } else {
      ElMessage.info('已取消删除')
    }
  } finally {
    // 隐藏加载状态
    loadingIds.value = loadingIds.value.filter(id => id !== row.id)
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的员工')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条员工信息吗？`, 
      '提示', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 显示加载状态
    const selectedIds = selectedRows.value.map(row => row.id)
    selectedIds.forEach(id => {
      if (!loadingIds.value.includes(id)) {
        loadingIds.value.push(id)
      }
    })
     
    // 调用API批量删除（实际项目中取消注释）
    // await batchDeleteEmployees(selectedIds)
    
    // 重新获取数据
    await fetchTableData(currentPage.value, pageSize.value)
    
    // 清空选择
    selectedRows.value = []
    
    ElMessage.success(`成功删除 ${selectedIds.length} 条数据`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败，请重试')
    } else {
      ElMessage.info('已取消删除')
    }
  } finally {
    // 隐藏加载状态
    // loadingIds.value = loadingIds.value.filter(id => !selectedIds.includes(id))
  }
}

// 根据身份证号自动填充生日和性别 - 新增表单
const autoFillFromID = () => {
  const id = formData.IDnumber.trim()
  if (id.length === 18) {
    // 提取生日
    const year = id.substring(6, 10)
    const month = id.substring(10, 12)
    const day = id.substring(12, 14)
    formData.birthday = `${year}-${month}-${day}`
    
    // 提取性别
    const genderCode = parseInt(id.substring(16, 17))
    formData.gender = genderCode % 2 === 1 ? '男' : '女'
  }
}

// 根据身份证号自动填充生日和性别 - 编辑表单
const autoFillFromIDEdit = () => {
  const id = editFormData.IDnumber.trim()
  if (id.length === 18) {
    // 提取生日
    const year = id.substring(6, 10)
    const month = id.substring(10, 12)
    const day = id.substring(12, 14)
    editFormData.birthday = `${year}-${month}-${day}`
    
    // 提取性别
    const genderCode = parseInt(id.substring(16, 17))
    editFormData.gender = genderCode % 2 === 1 ? '男' : '女'
  }
}

// 选择岗位档级后自动填充工资和gradeid - 新增表单
const autoFillSalaryAndGradeId = () => {
  // 从树形数据中查找选中的档级
  const findLevelData = (tree: TreeData[], value: string): TreeData | null => {
    for (const node of tree) {
      if (node.value === value) {
        return node;
      }
      if (node.children && node.children.length > 0) {
        const found = findLevelData(node.children, value);
        if (found) return found;
      }
    }
    return null;
  };
  
  const selectedLevel = findLevelData(treeLevelData.value, formData.post_level);
  
  if (selectedLevel) {
    formData.base_pay = selectedLevel.salary || 0;
    formData.gradeid = selectedLevel.gradeid || 0;
    
    nextTick(() => {
      if (addFormRef.value) {
        addFormRef.value.clearValidate('base_pay');
      }
    });
  }
}

// 选择岗位档级后自动填充工资和gradeid - 编辑表单
const autoFillSalaryAndGradeIdEdit = () => {
  // 从树形数据中查找选中的档级
  const findLevelData = (tree: TreeData[], value: string): TreeData | null => {
    for (const node of tree) {
      if (node.value === value) {
        return node;
      }
      if (node.children && node.children.length > 0) {
        const found = findLevelData(node.children, value);
        if (found) return found;
      }
    }
    return null;
  };
  
  const selectedLevel = findLevelData(treeLevelData.value, editFormData.post_level);
  
  if (selectedLevel) {
    editFormData.base_pay = selectedLevel.salary || 0;
    editFormData.gradeid = selectedLevel.gradeid || 0;
    
    nextTick(() => {
      if (editFormRef.value) {
        editFormRef.value.clearValidate('base_pay');
      }
    });
  }
}

// ... existing code ...
// 提交新增表单
const submitAddForm = async () => {
  if (!addFormRef.value) return
  try {
    // 表单验证
    await addFormRef.value.validate()
    
    isAdding.value = true
    
    // 准备提交的数据
    const submitData = {
      name: formData.name,                // 姓名
      tel: formData.tel,                  // 手机号
      sex: formData.gender,               // 性别（男女）
      idcard: formData.IDnumber,          // 身份证号
      birthday: formData.birthday,        // 生日
      address: formData.address,          // 籍贯
      record: formData.record,            // 学历
      projectid: formData.project,        // 项目ID
      companyid: formData.company,        // 公司ID
      bank_card: formData.bank_card,      // 银行卡号
      bank: formData.bank,                // 开户行
      agreement_end: formData.agreement_end,  // 现合同到期时间
      agreement_num: formData.agreement_num,  // 现合同期限
      base_pay: formData .base_pay,        // 岗位工资
      gradeid: formData.gradeid,          // 岗位档级ID
      political_status: formData.political_status,  // 政治面貌
      layout: formData.layout,            // 用工形式
      status: formData.status,            // 员工状态
      entry_time: formData.entry_time     // 入职时间
    }

    // 调用API添加员工
    await addstaff(submitData)
    
    // 重新获取数据
    await fetchTableData(currentPage.value, pageSize.value)
    
    // 关闭表单
    handleCloseAddForm()
    
    ElMessage.success('员工添加成功')
  } catch (error) {
    if (error !== false) { // 排除表单验证失败的情况
      console.error('添加员工失败:', error)
      ElMessage.error('添加失败，请重试')
    }
  } finally {
    isAdding.value = false
  }
}
// ... existing code ...
// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return
  try {
    // 表单验证
    await editFormRef.value.validate()
    
    isAdding.value = true
    
    // 准备提交的数据
    const submitData = {
      id: editFormData.id,                // 员工ID
      name: editFormData.name,            // 姓名
      tel: editFormData.tel,              // 手机号
      sex: editFormData.gender,           // 性别（男女）
      idcard: editFormData.IDnumber,      // 身份证号
      birthday: editFormData.birthday,    // 生日
      address: editFormData.address,      // 籍贯
      record: editFormData.record,        // 学历
      projectid: editFormData.project,    // 项目ID
      companyid: editFormData.company,    // 公司ID
      bank_card: editFormData.bank_card,  // 银行卡号
      bank: editFormData.bank,            // 开户行
      agreement_end: editFormData.agreement_end,  // 现合同到期时间
      agreement_num: editFormData.agreement_num,  // 现合同期限
      base_pay: editFormData.base_pay,    // 岗位工资
      gradeid: editFormData.gradeid,      // 岗位档级ID
      political_status: editFormData.political_status,  // 政治面貌
      layout: editFormData.layout,        // 用工形式
      status: editFormData.status,        // 员工状态
      entry_time: editFormData.entry_time // 入职时间
    }
    

    // 调用API更新员工信息（实际项目中实现）
    await editstaff(submitData)
    
    // 重新获取数据
    await fetchTableData(currentPage.value, pageSize.value)
    
    // 更新当前选中员工信息
    if (selectedEmployee.value && selectedEmployee.value.id === editFormData.id) {
      selectedEmployee.value = { ...selectedEmployee.value, ...submitData };
      fillViewFormData(selectedEmployee.value);
    }
    
    // 关闭表单
    handleCloseEditForm()
    
    ElMessage.success('员工信息更新成功')
  } catch (error) {
    if (error !== false) { // 排除表单验证失败的情况
      console.error('更新员工失败:', error)
      ElMessage.error('更新失败，请重试')
    }
  } finally {
    isAdding.value = false
  }
}

// 关闭新增表单时重置
const handleCloseAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  showAddForm.value = false
}

// 关闭编辑表单时重置
const handleCloseEditForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  showEditForm.value = false
}



// 监听员工状态变化 - 新增表单
watch(() => formData.status, (newVal) => {
  if (newVal === '2' && !formData.leave_time) {
    formData.leave_time = dayjs().format('YYYY-MM-DD')
  }
})

// 监听员工状态变化 - 编辑表单
watch(() => editFormData.status, (newVal) => {
  if (newVal === '2' && !editFormData.leave_time) {
    editFormData.leave_time = dayjs().format('YYYY-MM-DD')
  }
})

// 初始化加载数据
onMounted(() => {
  fetchTableData();
  fetchOrgTreeData();
  fetchLevelListData();
  
  getRoleList().then((res: any) => {
    console.log('角色列表:', res)
  }).catch((err: any) => {
    console.error('获取角色列表失败:', err)
  })
})

// 处理合同操作点击事件
const handleClick = () => {
  ElMessage.success('签署操作已发起');
}

// ... existing code ...
// 获取组织架构数据
const fetchOrgTreeData = async () => {
  try {
    const res = await getOrgTree({})
    if (res.data && res.companylist) {
      companyOptions.value = res.companylist.map((item: any) => ({
        value: String(item.id),
        label: item.account
      }))
      // 初始化过滤后的公司选项
      filteredCompanyOptions.value = [...companyOptions.value]
    }

    // 修改项目数据处理逻辑，遍历所有公司并处理每个公司的项目数组
    if (res.data && Array.isArray(res.data)) {
      // 创建一个空数组来存储所有项目
      let allProjects: any[] = [];
      
      // 遍历所有公司数据
      res.data.forEach((company: any) => {
        // 检查该公司是否有项目数组且为数组格式
        if (company.project && Array.isArray(company.project)) {
          // 将该项目数组合并到总项目数组中
          allProjects = allProjects.concat(company.project.map((item: any) => ({
            ...item,
            companyId: String(company.id || company.companyid || ''), // 关联公司ID
            companyTitle: company.title || company.account || '' // 公司名称
          })));
        }
      });
      
      // 构建项目选项列表
      projectOptions.value = allProjects.map((item: any) => ({
        value: String(item.id),
        label: `${item.title} (${item.companyTitle})`, // 项目名称(公司名称)
        companyId: String(item.companyId || item.companyid || '') // 关联公司ID
      }));
    }
  } catch (error) {
    console.error('获取组织架构数据失败:', error)
    ElMessage.error('获取组织架构数据失败')
  }
}

// 过滤公司选项（支持搜索）
const filterCompanyOptions = (query: string) => {
  if (!query) {
    filteredCompanyOptions.value = [...companyOptions.value]
    return
  }

  filteredCompanyOptions.value = companyOptions.value.filter(item => 
    item.label.toLowerCase().includes(query.toLowerCase())
  )
}

// 当公司选择框可见性改变时触发
const onCompanySelectVisibleChange = (visible: boolean) => {
  // 当下拉框打开时，确保显示所有选项
  if (visible) {
    if (!searchForm.company) {
      filteredCompanyOptions.value = [...companyOptions.value]
    } else {
      // 如果已经有搜索词，保持当前过滤结果
      filteredCompanyOptions.value = companyOptions.value.filter(item => 
        item.label.toLowerCase().includes(searchForm.company.toLowerCase())
      )
    }
  }
}

// 当清空公司选择时
const onCompanySelectClear = () => {
  searchForm.company = ''
  filteredCompanyOptions.value = [...companyOptions.value]
  handleSearch()
}

// 获取档级列表数据并转换为树形结构
const fetchLevelListData = async () => {
  try {
    const res = await getLevelList({})
    console.log(res);
    
    // 保存原始数据
    rawLevelData.value = res.list || [];
    
    // 转换为树形结构
    treeLevelData.value = convertToTree(rawLevelData.value);
    
  } catch (error) {
    console.error('获取档级列表失败:', error)
    ElMessage.error('获取档级列表失败')
  }
}

// 合同相关数据和方法
const showAddContractForm = ref(false)
const contractFormRef = ref<InstanceType<typeof ElForm>>()
const fileList = ref<any[]>([])

// 合同表单数据
const contractFormData = reactive({
  contractName: '',
  contractType: '',
  contractNumber: '',
  partyAName: '',
  partyAIdCard: '',
  partyAPhone: '',
  partyACompany: '',
  partyAOrgCode: '',
  partyBName: '',
  partyBIdCard: '',
  partyBPhone: '',
  executionStatus: '',
  startDate: '',
  endDate: '',
  contractFile: null as any
})

// 合同表单验证规则
const contractFormRules = reactive({
  contractName: [
    { required: true, message: '请输入合同名称', trigger: 'blur' }
  ],
  contractType: [
    { required: true, message: '请选择合同类型', trigger: 'change' }
  ],
  contractNumber: [
    { required: true, message: '请输入合同编号', trigger: 'blur' }
  ],
  partyAName: [
    { required: true, message: '请输入甲方姓名', trigger: 'blur' }
  ],
  partyAIdCard: [
    { required: true, message: '请输入甲方身份证号', trigger: 'blur' },
    { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号格式', trigger: 'blur' }
  ],
  partyAPhone: [
    { required: true, message: '请输入甲方手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  partyACompany: [
    { required: true, message: '请输入甲方公司全称', trigger: 'blur' }
  ],
  partyAOrgCode: [
    { required: true, message: '请输入甲方机构代码', trigger: 'blur' }
  ],
  partyBName: [
    { required: true, message: '乙方姓名不能为空', trigger: 'blur' }
  ],
  partyBIdCard: [
    { required: true, message: '乙方身份证号不能为空', trigger: 'blur' }
  ],
  partyBPhone: [
    { required: true, message: '乙方手机号不能为空', trigger: 'blur' }
  ],
  executionStatus: [
    { required: true, message: '请选择执行状态', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  contractFile: [
    { required: true, message: '请上传合同文件', trigger: 'change' }
  ]
})

// 打开合同新增弹窗
const openAddContractForm = () => {
  // 从选中的员工信息自动填充乙方信息
  if (selectedEmployee.value) {
    contractFormData.partyBName = selectedEmployee.value.name || ''
    contractFormData.partyBIdCard = selectedEmployee.value.idcard || ''
    contractFormData.partyBPhone = selectedEmployee.value.tel || ''
  }
  
  // 生成默认合同编号 (示例: HT+年月日+随机数)
  // const dateStr = dayjs().format('YYYYMMDD')
  // const randomStr = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  // contractFormData.contractNumber = `HT${dateStr}${randomStr}`
  
  showAddContractForm.value = true
}

// 关闭合同新增表单时重置
const handleCloseAddContractForm = () => {
  if (contractFormRef.value) {
    contractFormRef.value.resetFields()
  }
  fileList.value = []
  showAddContractForm.value = false
}
interface ContractData {
  date: string;
  name: string;
  state: string;
  city: string;
  address: string;
  zip: string;
}
const contractData = ref<ContractData[]>([])
// 提交合同新增表单
const submitAddContractForm = async () => {
  if (!contractFormRef.value) return
  
  try {
    // 表单验证
    await contractFormRef.value.validate()
    
    // 显示加载状态
    isAdding.value = true
    
    // 准备提交的数据
    const submitData = {
      contractName: contractFormData.contractName,
      contractType: contractFormData.contractType,
      contractNumber: contractFormData.contractNumber,
      partyAName: contractFormData.partyAName,
      partyAIdCard: contractFormData.partyAIdCard,
      partyAPhone: contractFormData.partyAPhone,
      partyACompany: contractFormData.partyACompany,
      partyAOrgCode: contractFormData.partyAOrgCode,
      partyBName: contractFormData.partyBName,
      partyBIdCard: contractFormData.partyBIdCard,
      partyBPhone: contractFormData.partyBPhone,
      executionStatus: contractFormData.executionStatus,
      startDate: contractFormData.startDate,
      endDate: contractFormData.endDate,
      // 文件上传后的服务器路径
      contractFileUrl: contractFormData.contractFile ? contractFormData.contractFile.url : '',
      // 关联员工ID
      employeeId: selectedEmployee.value?.id || 0
    }
    
    // 调用API添加合同
    await addCert(submitData)
    
    // 将新增的合同添加到contractData中
    contractData.value.push({
      date: contractFormData.contractName,
      name: contractFormData.partyBName,
      state: getContractTypeText(contractFormData.contractType),
      city: contractFormData.startDate,
      address: contractFormData.endDate,
      zip: '待签署'
    })
    
    // 刷新合同列表数据
    // fetchContractData()
  // 关闭表单
    handleCloseAddContractForm()
    
    ElMessage.success('合同添加成功')
  } catch (error) {
    if (error !== false) { // 排除表单验证失败的情况
      console.error('添加合同失败:', error)
      ElMessage.error('添加失败，请重试')
    }
  } finally {
    isAdding.value = false
  }
}

// 证书类型数据
const certificateTypes = [
  { value: '1', label: '毕业证' },
  { value: '2', label: '电工证lsq' },
  { value: '3', label: '驾驶证' },
  { value: '4', label: '荣誉证' },
  { value: '5', label: '技工证' },
  { value: '6', label: '学位证' }
]

// 证书表单数据
const certificateFormData = reactive({
  name: '',
  level: '',
  issueDate: '',
  reviewDate: '',
  image: null as any
})

// 证书表单引用
const certificateFormRef = ref<InstanceType<typeof ElForm>>()

// 显示证书新增表单
const showAddCertificateForm = ref(false)

// 打开新增证书表单
const openAddCertificateForm = (cert: {value: string, label: string}) => {
  certificateFormData.name = cert.label
  showAddCertificateForm.value = true
}

// 关闭新增证书表单
const handleCloseAddCertificateForm = () => {
  if (certificateFormRef.value) {
    certificateFormRef.value.resetFields()
  }
  showAddCertificateForm.value = false
}

// 提交证书表单
const submitCertificateForm = async () => {
  if (!certificateFormRef.value) return
  
  try {
    await certificateFormRef.value.validate()
    // 这里应该调用API保存证书信息
    ElMessage.success('证书保存成功')
    handleCloseAddCertificateForm()
  } catch (error) {
    if (error !== false) {
      console.error('保存证书失败:', error)
      ElMessage.error('保存失败，请重试')
    }
  }
}

// 删除证书
const deleteCertificate = async () => {
  try {
    await ElMessageBox.confirm('确定要删除该证书吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 这里应该调用API删除证书
    ElMessage.success('证书删除成功')
    handleCloseAddCertificateForm()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除证书失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 文件上传成功处理
const handleCertificateUploadSuccess = (response: any, file: any) => {
  if (response.success) {
    certificateFormData.image = {
      name: file.name,
      url: response.data.url
    }
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败: ' + (response.message || '未知错误'))
  }
}

// 文件上传失败处理
const handleCertificateUploadError = (error: any) => {
  console.error('图片上传错误:', error)
  ElMessage.error('图片上传失败，请重试')
}

// 处理文件超出限制
const handleCertificateExceed = (files: File[], fileList: any[]) => {
  ElMessage.warning(`只能上传一张图片`)
}

// 工资社保月份选择器
const value2 = ref('')
</script>

<style scoped>
.staff_box{
  background-color:#fff;
  padding: 20px;
}
.search-add{
  display:flex;
  margin-top:2%;
}

.input{
  width:13%;
  height:40px;
  margin-left:1%;
}
.staff_function{
  width: 100%;
  margin-top: 15px;
  .item{
    margin-left: 20px;
  }
}
 .staff_title{
  background: #fff;
  width: 100%;
  height: 60px;
  font-size: 24px;
  font-weight: 500;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}
.add_box {
  margin-left: auto;
}
/* 表单样式 */
.add-form {
  margin-top: 15px;
}
.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}
.el-form-item {
  flex: 1;
  min-width: 200px;
  max-width: calc(33.333% - 20px);
}
/* 表格 */
.employee-table-container {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  flex-wrap: wrap;
}

/* 优化表格列宽和样式 */
.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分页样式优化 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
  border-top: 1px solid #eee;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
  margin-right: 15px;
}

.el-pagination {
  margin: 0;
}

/* 表格行悬停效果优化 */
:deep(.el-table__row:hover > td) {
  background-color: #f5f7fa !important;
}

/* 当前行高亮样式 */
:deep(.el-table__row.current-row > td) {
  background-color: #e6f7ff !important;
}

/* 筛选按钮高亮样式 */
:deep(.active-filter-btn) {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

/* 详情页样式 */
.tab-content {
  padding: 15px;
}

h3 {
  margin: 10px 0 20px 0;
  color: #303133;
}

h4 {
  margin: 15px 0;
  color: #606266;
}

/* 抽屉样式优化 */
:deep(.custom-drawer .el-drawer__header) {
  padding: 16px 24px;
  border-bottom: none !important;
}

:deep(.custom-drawer .el-drawer__body) {
  padding: 24px;
  overflow: auto;
}

/* 抽屉头部样式 */
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.edit-button {
  color: #0052CC;
  font-size: 14px;
  cursor: pointer;
}

/* 移除抽屉边框 */
:deep(.el-drawer__container .el-drawer) {
  box-shadow: none !important;
  border-left: none !important;
}

/* 基本信息查看表单样式 */
:deep(.el-form-item__content .el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  color: #606266;
}

:deep(.el-form-item__content .el-select.is-disabled .el-select__inner) {
  background-color: #f5f7fa;
  color: #606266;
}

:deep(.el-form-item__content .el-date-picker.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  color: #606266;
  color: #606266;
}

/* 合同上传区域样式 */
:deep(.upload-demo) {
  margin-top: 10px;
}

:deep(.el-upload__tip) {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}
/* 证书卡片样式 */
.certificate-cards-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
  margin-top: 20px;
}

.certificate-card {
  width: calc(33.333% - 20px);
  height: 120px;
  background-color: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.certificate-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.certificate-name {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
  text-align: center;
}

@media (max-width: 100%) {
  .certificate-card {
    width: calc(100%);
  }
}

@media (max-width: 100%) {
  .certificate-card {
    width: 100%;
  }
}

/* 表单样式 */
.add-form {
  margin-top: 15px;
}
.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}
.el-form-item {
  flex: 1;
  min-width: 200px;
  max-width: calc(33.333% - 20px);
}
/* 表格 */
.employee-table-container {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  flex-wrap: wrap;
}

/* 优化表格列宽和样式 */
.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分页样式优化 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
  border-top: 1px solid #eee;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
  margin-right: 15px;
}

.el-pagination {
  margin: 0;
}

/* 表格行悬停效果优化 */
:deep(.el-table__row:hover > td) {
  background-color: #f5f7fa !important;
}

/* 当前行高亮样式 */
:deep(.el-table__row.current-row > td) {
  background-color: #e6f7ff !important;
}

/* 筛选按钮高亮样式 */
:deep(.active-filter-btn) {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

/* 详情页样式 */
.tab-content {
  padding: 15px;
}

h3 {
  margin: 10px 0 20px 0;
  color: #303133;
}

h4 {
  margin: 15px 0;
  color: #606266;
}

/* 抽屉样式优化 */
:deep(.custom-drawer .el-drawer__header) {
  padding: 16px 24px;
  border-bottom: none !important;
}

:deep(.custom-drawer .el-drawer__body) {
  padding: 24px;
  overflow: auto;
}

/* 抽屉头部样式 */
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.edit-button {
  color: #0052CC;
  font-size: 14px;
  cursor: pointer;
}

/* 移除抽屉边框 */
:deep(.el-drawer__container .el-drawer) {
  box-shadow: none !important;
  border-left: none !important;
}

/* 基本信息查看表单样式 */
:deep(.el-form-item__content .el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  color: #606266;
}

:deep(.el-form-item__content .el-select.is-disabled .el-select__inner) {
  background-color: #f5f7fa;
  color: #606266;
}

:deep(.el-form-item__content .el-date-picker.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  color: #606266;
  color: #606266;
}

/* 合同上传区域样式 */
:deep(.upload-demo) {
  margin-top: 10px;
}

:deep(.el-upload__tip) {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}
</style>
